
//
//  BDDetailLoginTableViewCell.m
//  BadBoy
//
//  Created by wen on 2017/3/11.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDDetailLoginTableViewCell.h"

@interface BDDetailLoginTableViewCell ()
{
    BOOL isFirst;
    BOOL isLast;
    
    BOOL clickGetButton;
    UIColor *finishColor;
}
@property (nonatomic, strong) UIButton *getButton;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIView *upLine;
@property (nonatomic, strong) UIView *downLine;


@end

@implementation BDDetailLoginTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        [[self.getButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            NSDictionary *para = @{@"mobile":self.textField.text};
            NSString *url = [NSString stringWithFormat:@"%@sms", KBDBaseURL];
            clickGetButton = YES;
            self.getButton.userInteractionEnabled = NO;
            
            RACCommand *getCodeCommand = [BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO];
            RACSignal *getCodeSignal = [getCodeCommand execute:nil];
            [getCodeSignal subscribeNext:^(id  _Nullable x) {
                @weakify(self);
                __block NSInteger number = 60;
                NSInteger numberLimit = number;
                RACSignal *timeSignal = [[[[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]] take:numberLimit] startWith:[NSDate date]] map:^id(NSDate *date) {
                    @strongify(self);
                    if (number == 0) {
                        [self.getButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
                        self.getButton.userInteractionEnabled = YES;
                        clickGetButton = NO;
                        self.getButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
                        return @YES;
                    }else{
                        [self.getButton setTitle:[NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number] forState:UIControlStateNormal];
                        //                    // BDLog(ASLocalizedString(@"按钮文本是什么：%@"), [NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number]);
                        number--;
                        return @NO;
                    }
                }] takeUntil:self.rac_willDeallocSignal];
                
                _getButton.rac_command = [[RACCommand alloc]initWithEnabled:timeSignal signalBlock:^RACSignal *(id input) {
                    number = numberLimit;
                    return timeSignal;
                }];
            }];
            
            [getCodeSignal subscribeError:^(NSError * _Nullable error) {
                [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:ASLocalizedString(@"发送验证码失败，请稍后再试")clickHidden:NO clickBlock:nil];
                [self.getButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
                self.getButton.userInteractionEnabled = YES;
                clickGetButton = NO;
                self.getButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
            }];
        }];
    }
    return self;
}

- (void)configeWithDic:(NSDictionary *)dic editBlock:(void(^)(NSString *str))editBlock{
    self.textLabel.text = dic[@"title"];
    if ([self.textLabel.text isEqualToString:ASLocalizedString(@"手机号码")] || [self.textLabel.text isEqualToString:ASLocalizedString(@"验证码")]) {
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
    }else{
        self.textField.keyboardType = UIKeyboardTypeDefault;
    }
    if ([self.textLabel.text isEqualToString:ASLocalizedString(@"邀请码")]) {
        self.textField.placeholder = ASLocalizedString(@"请输入8位数字的邀请码（可不填）");
        self.textField.keyboardType = UIKeyboardTypeNumberPad;
        [self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    if (dic[@"image"]) {
        UIImage *image = [UIImage imageNamed:dic[@"image"]];
        
        if (image) {
            self.imageView.image = image;
        }else if ((image = [UIImage imageWithContentsOfFile:dic[@"image"]])) {
            self.imageView.image = image;
        }else {
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:dic[@"image"]] placeholderImage:nil];
        }
        self.imageView.hidden = NO;
        self.textField.hidden = YES;
        self.getButton.hidden = YES;
        self.detailTextLabel.hidden = YES;
    }else{
        self.imageView.hidden = YES;
        self.textField.hidden = NO;
        if (dic[@"subTitle"]) {
            self.textField.text = dic[@"subTitle"];
        }
        if (dic[@"getCode"]) {
            self.getButton.hidden = NO;
        }else{
            self.getButton.hidden = YES;
        }
    }
    isFirst = dic[@"first"] ? YES : NO;
    isLast = dic[@"last"] ? YES : NO;
    
    [self.textField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if ([self.textLabel.text isEqualToString:ASLocalizedString(@"邀请码")]) {
            editBlock(x);
        }else{
            editBlock(x);
            BOOL resu = x.length == 11;
            
            self.getButton.userInteractionEnabled = resu;
            if (clickGetButton == NO) {
                self.getButton.backgroundColor = resu ? kCodeButtonColor : kNOValidColor;
            }else{
                finishColor = resu ? kCodeButtonColor : kNOValidColor;
            }
        }
    }];
    
}

-(void)textFieldDidChange:(UITextField *)sender{
    if ([self.textLabel.text isEqualToString:ASLocalizedString(@"邀请码")]) {
        if (sender == self.textField) {
            if (sender.text.length > 8) {
                sender.text = [sender.text substringToIndex:8];
            }
        }
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.imageView.size = CGSizeMake(52, 52);
    self.imageView.right = self.width - 10;
    self.imageView.centerY = self.height / 2.0;
    
    self.textLabel.font = [UIFont systemFontOfSize:15];
    self.textLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
    self.textLabel.left = 10;
    
    self.detailTextLabel.font = [UIFont systemFontOfSize:14];
    self.detailTextLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    self.detailTextLabel.right = self.width - 10;
    
    self.getButton.right = self.width - 10;
    self.getButton.centerY = self.height / 2.0;
    
    if (self.getButton.hidden == YES) {
        self.textField.width = self.getButton.right - 100;
    }else{
        self.textField.width = self.getButton.left - 10 - 100;
    }
    self.textField.height = self.height;
    self.textField.left = 100;
    //    self.textField.backgroundColor = [UIColor yellowColor];
    
    
    self.upLine.hidden = NO;
    
    if (isLast) {
        self.downLine.hidden = NO;
    }else{
        self.downLine.hidden = YES;
    }
}

- (UIButton *)getButton{
    if (!_getButton) {
        self.getButton = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = ASLocalizedString(@"获取验证码");
        [_getButton setTitle:title forState:UIControlStateNormal];
        _getButton.backgroundColor = kNOValidColor;
        _getButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _getButton.width = 90;
        _getButton.height = 35;
        _getButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        _getButton.layer.masksToBounds = YES;
        _getButton.layer.cornerRadius = 4;
        [self.contentView addSubview:_getButton];
    }
    return _getButton;
}

- (UIView *)upLine{
    if (!_upLine) {
        self.upLine = [[UIView alloc] init];
        _upLine.size = CGSizeMake(self.width, 0.5);
        _upLine.backgroundColor = kBDColorGray;
        [self.contentView addSubview:_upLine];
    }
    return _upLine;
}

- (UIView *)downLine{
    if (!_downLine) {
        self.downLine = [[UIView alloc] init];
        _downLine.size = CGSizeMake(self.width, 0.5);
        _downLine.left = 10;
        _downLine.bottom = self.height;
        _downLine.backgroundColor = kBDColorGray;
        [self.contentView addSubview:_downLine];
    }
    return _downLine;
}

- (UITextField *)textField{
    if (!_textField) {
        self.textField = [[UITextField alloc] init];
        _textField.font = [UIFont systemFontOfSize:13];
        _textField.tintColor = [UIColor lightGrayColor];
        _textField.borderStyle = UITextBorderStyleNone;
        [self.contentView addSubview:_textField];
    }
    return _textField;
}

@end
